package com.lin.operatorlogrecord.service.impl;

import com.lin.operatorlogrecord.entity.enums.LogTypeEnum;
import com.lin.operatorlogrecord.entity.enums.ObjectTypeEnum;
import com.lin.operatorlogrecord.entity.model.OperatorLog;
import com.lin.operatorlogrecord.entity.vo.OperatorLogVO;
import com.lin.operatorlogrecord.mapper.OperatorLogMapper;
import com.lin.operatorlogrecord.service.IOperatorLogService;
import com.lin.operatorlogrecord.unit.OperatorLogQueryUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: chenghao.lin
 * @Date: 2023/09/21
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class OperatorLogServiceImpl implements IOperatorLogService {

    private final OperatorLogMapper operatorLogMapper;
    @Override
    public List<OperatorLogVO> list(LogTypeEnum logTypeEnum) {
        List<OperatorLog> operatorLogs = operatorLogMapper.listByType(logTypeEnum);
        List<OperatorLogVO> operatorLogVOS = packOperatorLogVO(operatorLogs);
        // 填充操作者
        // 填充操作对象名称
        fillOperatorObjName(operatorLogVOS);
        return operatorLogVOS;
    }

    /**
     * 填充操作对象名称
     * @param operatorLogVOS
     */
    private void fillOperatorObjName(List<OperatorLogVO> operatorLogVOS) {
        // 根据对象类型分类
        Map<ObjectTypeEnum, List<OperatorLogVO>> operatorTypeMap = operatorLogVOS.stream().collect(Collectors.groupingBy(OperatorLogVO::getOperatorObjType));
        for (Map.Entry<ObjectTypeEnum, List<OperatorLogVO>> entry : operatorTypeMap.entrySet()) {
            List<OperatorLogVO> value = entry.getValue();
            // 获取操作对象Id，去重和去掉null
            List<String> operatorObjIds = value.stream().map(OperatorLogVO::getOperatorObjId).distinct().filter(Objects::nonNull).collect(Collectors.toList());
            ObjectTypeEnum key = entry.getKey();
            Map<String, String> operatorObjIdMap = OperatorLogQueryUtil.listObjIdAndNameMap(operatorObjIds, key);
            for (OperatorLogVO operatorLogVO : value) {
                operatorLogVO.setOperatorObjName(operatorObjIdMap.get(operatorLogVO.getOperatorObjId()));
            }
        }
    }

    public List<OperatorLogVO> packOperatorLogVO(List<OperatorLog> operatorLogs) {
        List<OperatorLogVO> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(operatorLogs)) {
            return result;
        }
        for (OperatorLog operatorLog : operatorLogs) {
            OperatorLogVO operatorLogVO = new OperatorLogVO();
            BeanUtils.copyProperties(operatorLog, operatorLogVO);
            result.add(operatorLogVO);
        }
        return result;
    }
}
